//
//  AuthViewController.m
//  01 微博
//
//  Created by zhoup on 16/5/18.
//  Copyright © 2016年 zhoup. All rights reserved.
//

#import "AuthViewController.h"
#import "MBProgressHUD+MJ.h"
#import "AFHTTPSessionManager.h"
#import "WPAccount.h"

@interface AuthViewController ()<UIWebViewDelegate>

@end


@implementation AuthViewController

//使用UIWebView 来加载登录页面
-(void)loadView
{
    self.view  = [[UIWebView alloc]init];
}

- (void)viewDidLoad {
    [super viewDidLoad];
  
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    
    // 2.加载登录页面
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@", WPAppKey, WPRedirectURI];
    
    NSLog(@"urlstr = %@",urlStr);
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    UIWebView *webView = (UIWebView *)self.view;
    //第一次出现登录界面
    [webView loadRequest:request];
    
    // 输入用户名和密码以后 需要解析结果 获取code
    webView.delegate = self;
    
}

//取消登录
-(void)close
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    // 1.获得请求地址
    NSString *url = request.URL.absoluteString;
    NSLog(@"ur; = %@",url);
    // 2.判断url是否为回调地址
    NSString *str = [NSString stringWithFormat:@"%@/?code=", WPRedirectURI];
    NSRange range = [url rangeOfString:str];
    if (range.location != NSNotFound) { // 是回调地址
        // 截取授权成功后的请求标记
        int from = range.location + range.length;
        NSString *code = [url substringFromIndex:from];
        
        // 根据code获得一个accessToken
        [self accessTokenWithCode:code];
        
        // 禁止加载回调页面
        return NO;
    }
    
    return YES;
}
/**
 *  UIWebView开始加载资源的时候调用(开始发送请求)
 */
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [MBProgressHUD showMessage:@"正在加载中..."];
}

/**
 *  UIWebView加载完毕的时候调用(请求完毕)
 */
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [MBProgressHUD hideHUD];
    
}
/**
 *  UIWebView加载失败的时候调用(请求失败)
 */
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error
{
    [MBProgressHUD hideHUD];
}


/**
 *  根据code获得一个accessToken(发送一个POST请求)
 *
 *  @param code 授权成功后的请求标记
 */
- (void)accessTokenWithCode:(NSString *)code
{
    // 1.封装请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"client_id"] = WPAppKey;
    params[@"client_secret"] = WPAppSecret;
    params[@"redirect_uri"] = WPRedirectURI;
    params[@"grant_type"] = @"authorization_code";
    params[@"code"] = code;
    // 2.获得请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes
    = [NSSet setWithObject:@"text/plain"];
    // 2.发送GET请求
    [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
         NSLog(@"access_token success");
        
        WPAccount *account = [[WPAccount alloc]init];
        account.access_token = responseObject[@"access_token"];
        account.uid = responseObject[@"uid"];
        
        [account save];
        
        [WPAccount saveLoginStatus];
        
        NSLog(@"%@",responseObject);
        /*
         "access_token" = "2.00AJ4OJEliTUSCa9b954f33bC6VieB";
         "expires_in" = 124669; //过期时间
         "remind_in" = 124669;
         uid = 3800943914; //当前用户的ID
         }
         */
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"access_token faile");
    }];
}



@end
